package core

import (
	"bufio"
	"fmt"
	"io"
	"mytool/base"
	"net/http"
	"os"
	"strings"
	"time"
)

const NavBegin = `<!doctype html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>mytool:网站导航</title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }

        body {
            background: white;
        }

        .header {
            position: relative;
            height: 300px;
        }

        select, option {
            outline: none;
            border: none;
            background: #f0f0f0;
        }

        .search {
            position: absolute;
            width: 500px;
            left: 50%;
            bottom: 64px;
            margin-left: -250px;
        }

        .search-wrapper {
            display: flex;
        }

        .search-wrapper input {
            flex: 1;
            height: 40px;
            outline: none;
            border: 2px solid transparent;
            border-radius: 20px;
            padding: 0 44px 0 10px;
            float: left;
            font-size: 16px;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
        }


        .search-wrapper button {
            width: 44px;
            height: 44px;
            margin-left: -44px;
            outline: none;
            border: none;
            border-radius: 0 20px 20px 0;
            background: #f0f0f0;
            color: white;
            font-weight: bold;
            cursor: pointer;
        }

        .guid {
            width: 650px;
            margin: 0 auto;
        }

        .guid a {
            float: left;
            font-size: 12px;
            padding: 10px;
            border-radius: 15px;
            margin: 5px;
            text-decoration: none;
            cursor: pointer;
            color: #0095ff;
        }

        .guid a:hover {
            color: white;
            background: #0095ff;
        }

    </style>
</head>
<body>
<div class="header">
    <div style="font-size: 12px; height: 20px;line-height: 20px;margin: 10px 0 0 10px; padding-left:10px; border-left: 5px solid #0095ff;">
        mytool#网站导航
    </div>
    <div class="search">
        <div style="height: 88px; line-height: 88px; text-align: center;font-size: 22px; font-weight: bold; color: #f0f0f0">
            <span style="color: #0095ff">网站导航</span>
        </div>
        <div class="search-wrapper">
            <input type="text" id="search">
            <button onclick="doClick()">🔍</button>
        </div>
    </div>
</div>
<div class="guid">`

const NavEnd = `</div>
</body>
</html>
<script>
    function doClick() {
        window.location.href = 'https://cn.bing.com/search?q=' + document.getElementById("search").value
    }
</script>`

type SiteItem struct {
	Category string
	Name     string
	Url      string
}

var SiteList []*SiteItem

func readConfig(path string) error {
	// 检查配置文件是否存在
	fp, err := os.Open(path)
	if err != nil {
		return err
	}
	defer fp.Close()

	reader := bufio.NewReader(fp)
	for {
		// 读取一行数据
		line, _, err := reader.ReadLine()
		if err == io.EOF {
			break
		}
		if err != nil {
			return err
		}

		// 配置格式：search,baidu,https://www.baidu.com
		arr := strings.Split(string(line), ",")
		if len(arr) != 3 {
			continue
		}

		SiteList = append(SiteList, &SiteItem{arr[0], arr[1], arr[2]})
	}

	return nil
}

func Nav(args []string) (err error) {
	// 读取配置文件
	path := "nav.dat"
	port := "80"

	if len(args) > 1 {
		path = args[1]
	}

	if len(args) == 3 {
		port = args[2]
	}

	if err := readConfig(path); err != nil {
		return err
	}

	// 注册一个http callback
	http.HandleFunc("/", func(writer http.ResponseWriter, request *http.Request) {
		// 向浏览器发送数据
		writer.Header().Add("Content-Type", "text/html")
		writer.Write([]byte(NavBegin))
		for _, v := range SiteList {
			writer.Write([]byte(fmt.Sprintf(`<a href="%s">%s</a>`, v.Url, v.Name)))
		}
		writer.Write([]byte(NavEnd))
	})

	// 延迟打开
	go func() {
		time.Sleep(time.Second * 2)
		OpenUrl([]string{"open", "http://127.0.0.1:" + port})
	}()

	// start web
	return http.ListenAndServe(":"+port, nil)
}

func NavTool() *base.Option {
	return &base.Option{"nav", Nav, `nav [config_file port] 打开导航页 eg. nav d:\nav.dat 8080`}
}
